// stores/user.ts
import { defineStore } from 'pinia'

interface UserInfo {
  id: number
  username: string
  usertype: number 
}

export const useUserStore = defineStore('user', {
  state: () => ({
    token: '',
    userInfo: {} as UserInfo,
  }),
  actions: {
    setToken(token: string) {
      this.token = token
      localStorage.setItem('token', token)
    },
    setUserInfo(info: UserInfo) {
      this.userInfo = info
      localStorage.setItem('userInfo', JSON.stringify(info))
    },
    logout() {
      this.token = ''
      this.userInfo = {} as UserInfo
      localStorage.removeItem('token')
      localStorage.removeItem('userInfo')
    },
    loadFromStorage() {
      const token = localStorage.getItem('token')
      const userInfo = localStorage.getItem('userInfo')

      this.token = token || ''
      try {
        this.userInfo = userInfo ? JSON.parse(userInfo) : {} as UserInfo
      } catch (e) {
        console.warn('❗本地 userInfo JSON 解析失败，已清除')
        localStorage.removeItem('userInfo')
        this.userInfo = {} as UserInfo
      }
    },
  },
})